package com.cloudkinto.service.mail.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.RabbitQueueConstant;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.dto.platform.order.PlatformOrderDto;
import com.cloudkinto.entity.*;
import com.cloudkinto.enumType.operate.OperateTypeEnum;
import com.cloudkinto.service.mail.MailAccountService;
import com.cloudkinto.service.mail.MailSenderService;
import com.cloudkinto.service.mail.SendMailService;
import com.cloudkinto.service.mail.vo.SendMailReq;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.cloudkinto.common.constant.GlobalConstants.SEND_MAIL_FAIL;
import static com.cloudkinto.common.constant.GlobalConstants.SEND_MAIL_SUCCESS;

@Service
public class SendMailServiceImpl implements SendMailService {
    private static final Logger logger = LoggerFactory.getLogger(SendMailServiceImpl.class);
    @Autowired
    private FreeMarkerTemplateDao freeMarkerTemplateDao;
    @Autowired
    private PlatformOrderDao platformOrderDao;
    @Autowired
    private LogisticsChannelDao logisticsChannelDao;
    @Autowired
    private PlatformOrderProductDao platformOrderProductDao;
    @Autowired
    private MailSenderService mailSenderService;
    @Autowired
    private FreeMarkerTemplatePlaceHolderDao freeMarkerTemplatePlaceHolderDao;
    @Autowired
    private PlatformStoreDao platformStoreDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailAccountService mailAccountService;
    @Autowired
    private MailAccountDao mailAccountDao;
    @Autowired
    private ShopDao shopDao;

    @Autowired
    private MailRecordDao mailRecordDao;
    @Autowired
    private TemplatesDao templatesDao;

    @Autowired
    private TemplatesContentDao templatesContentDao;

    @Override
    public SingleResult sendEmail(SendMailReq req) {
        List<OperateRecordDo> operateRecordDos = new ArrayList<>();
        //List<MailRecordDo> mailRecordDos=new ArrayList<>();

        Session session = mailSenderService.initMailSession(req);
        Transport transport = mailSenderService.initMailTransport(session, req);
        Long templateId = req.getTemplateId();
        if (templateId == null) {
            return SingleResult.failure("模板id不能为空");
        }
        //PlatformOrderDo platformOrder = platformOrderDao.selectByPlatformOrderNo(req.getPlatformOrderNo());
        PlatformOrderDo platformOrder = platformOrderDao.selectById(req.getOrderId());
        String platformCode = platformOrder.getPlatformCode();
        PlatformOrderDto platformOrderDto = new PlatformOrderDto();
        List<PlatformOrderProductDo> platformOrderProductDos = platformOrderProductDao.selectList(new LambdaQueryWrapper<PlatformOrderProductDo>().eq(PlatformOrderProductDo::getOrderId, platformOrder.getId()));
        BeanUtils.copyProperties(platformOrder, platformOrderDto);
        platformOrderDto.setProductDoList(platformOrderProductDos);
        String mailNo = req.getMailNo();

        String message = sendUserEmail(templateId, platformOrderDto, mailNo);
//拼接头部，尾部内容
        Long storeId = req.getStoreId();
        Long mailAccountId = req.getId();
        message = getString(mailAccountId, message);
        //替换\n为<br>,为了渲染html
        message = message.replaceAll("\\n", "<br>");
        PlatformStoreDo platformStoreDo = platformStoreDao.selectById(storeId);
        // String storeName = platformStoreDo.getStoreName();
        //找到收件人邮箱
           String receiverEmail="1044155865@qq.com";
       //String receiverEmail = getReceiverEmail(req.getPlatformOrderNo());
        MailRecordDo mailRecordDo = new MailRecordDo();
        mailRecordDo= handleMailRecordDo(req,receiverEmail,platformCode);
        FreeMarkerTemplateDo freeMarkerTemplateDo = freeMarkerTemplateDao.selectById(templateId);
        String title = freeMarkerTemplateDo.getMailTitle();
        String context = req.getTitle();
        int emailTitleType = req.getEmailTitleType();
        //1:前缀, 2:后缀
        if (emailTitleType == 1) {
            title = context + title;
        } else if (emailTitleType == 2) {
            title = title + context;
        }

        //String mailTitle = freeMarkerTemplateDo.getMailTitle();


        try {
            mailSenderService.sendEmail(session, transport, title, message, mailNo, receiverEmail);
            mailRecordDo.setSendStatus(SEND_MAIL_SUCCESS);

            OperateRecordDo operateRecordDo = new OperateRecordDo(platformOrder.getId(), OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_SendMail,
                    null, new Date(), String.format("手动配信成功！"));
            operateRecordDos.add(operateRecordDo);
        } catch (Exception e) {
            mailRecordDo.setSendStatus(SEND_MAIL_FAIL);
            OperateRecordDo operateRecordDo = new OperateRecordDo(platformOrder.getId(), OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_SendMail,
                    null, new Date(), String.format("手动配信失败！"));
            operateRecordDos.add(operateRecordDo);
            throw new BizException("手动配信失败！");
        }finally {
            mailRecordDao.insert(mailRecordDo);
            try {
                transport.close();
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }

        //操作记录
        if (!operateRecordDos.isEmpty()) {
            List<List<OperateRecordDo>> partition = ListUtil.partition(operateRecordDos, 3000);
            for (List<OperateRecordDo> partList : partition) {
                rabbitTemplate.convertAndSend(RabbitQueueConstant.CrossMall_CMOrder_OperateList, JSON.toJSONString(partList));
            }
        }
        //  mailSenderService.sendEmail(session, transport, title, message, receiverEmail);
        return SingleResult.success(message);
    }

    private MailRecordDo handleMailRecordDo(SendMailReq req, String receiverEmail,String platformCode) {
        Long timesStamp = templatesDao.selectById(req.getTemplateId()).getTimesStamp();
        MailRecordDo mailRecordDo=new MailRecordDo();
        mailRecordDo.setTimesStamp(timesStamp);
        mailRecordDo.setTemplateId(req.getTemplateId());
        mailRecordDo.setRecipient(req.getReceiver());
        mailRecordDo.setStoreId(req.getStoreId());
        mailRecordDo.setPlatformOrderNo(req.getPlatformOrderNo());
        mailRecordDo.setMailNoSend(req.getMailNo());
        mailRecordDo.setMailNoReceive(receiverEmail);
        mailRecordDo.setDeleteFlag(0);
        mailRecordDo.setPlatformCode(platformCode);
        mailRecordDo.setOrderId(req.getOrderId());
        //设置方式为手动
        mailRecordDo.setSendMethod(0);
        mailRecordDo.setSendTime(new Date(System.currentTimeMillis()));
        return mailRecordDo;
    }

    private String getString(Long mailAccountId, String message) {

        List<MailAccountDo> mailAccountDos = mailAccountDao.selectList(new LambdaQueryWrapper<MailAccountDo>().eq(MailAccountDo::getId, mailAccountId));
        if (!mailAccountDos.isEmpty()) {
            MailAccountDo mailAccountDo = mailAccountDos.get(0);
            String tailContent = mailAccountDo.getTailContent();
            String headContent = mailAccountDo.getHeadContent();
            //把tailcontent放到message尾部
            if (StringUtils.isNotBlank(tailContent)) {
                message = message + tailContent;
            }
            //把headcontent放到message头部
            if (StringUtils.isNotBlank(headContent)) {
                message = headContent + message;
            }
        }
        return message;
    }

    @Override
    public SingleResult preview(SendMailReq req) {
        long currentTimeMillis = System.currentTimeMillis();
        Long templateId = req.getTemplateId();
        if (templateId == null) {
            return SingleResult.failure("模板id不能为空");
        }
        Long storeId = req.getStoreId();
        Long mailAccountId = req.getId();
        /*      PlatformOrderDo platformOrder = platformOrderDao.selectByPlatformOrderNo(req.getPlatformOrderNo());*/
        PlatformOrderDo platformOrder = platformOrderDao.selectById(req.getOrderId());
        PlatformOrderDto platformOrderDto = new PlatformOrderDto();
        List<PlatformOrderProductDo> platformOrderProductDos = platformOrderProductDao.selectList(new LambdaQueryWrapper<PlatformOrderProductDo>().eq(PlatformOrderProductDo::getOrderId, platformOrder.getId()));
        BeanUtils.copyProperties(platformOrder, platformOrderDto);
        platformOrderDto.setProductDoList(platformOrderProductDos);
        String message = sendUserEmail(templateId, platformOrderDto, req.getMailNo());
        message = getString(mailAccountId, message);
        message = message.replaceAll("\\n", "<br>");
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("耗时：" + (currentTimeMillis1 - currentTimeMillis));
        return SingleResult.success(message);

    }

    @Override
    public SingleResult previewContent(SendMailReq req) {
        long currentTimeMillis = System.currentTimeMillis();
        Long templateId = req.getTemplateId();
        if (templateId == null) {
            return SingleResult.failure("模板id不能为空");
        }
        Long storeId = req.getStoreId();
        PlatformOrderDo platformOrder = platformOrderDao.selectById(req.getOrderId());
        PlatformOrderDto platformOrderDto = new PlatformOrderDto();
        if(req.getOrderId()==null)
        {
            throw new BizException("平台单号为空,无法查看详情！");
        }
        List<PlatformOrderProductDo> platformOrderProductDos = platformOrderProductDao.selectList(new LambdaQueryWrapper<PlatformOrderProductDo>().eq(PlatformOrderProductDo::getOrderId, platformOrder.getId()));

        BeanUtils.copyProperties(platformOrder, platformOrderDto);
        platformOrderDto.setProductDoList(platformOrderProductDos);
        String message = sendUserEmail2(req, platformOrderDto);
        Long mailAccountId = req.getId();
        message = getString(mailAccountId, message);
        message = message.replaceAll("\\n", "<br>");
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("耗时：" + (currentTimeMillis1 - currentTimeMillis));
        return SingleResult.success(message);

    }


    @Override
    public void deleteRecordsOlderThan7Days() {
        mailRecordDao.delete(new LambdaQueryWrapper<MailRecordDo>()
                .lt(MailRecordDo::getSendTime, DateUtil.offsetDay(new Date(), -7)));
    }


    @Override
    public SingleResult autoSendEmail(int mailType, Long storeId, List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return null;
        }
        List<PlatformOrderDo> platformOrderDos = platformOrderDao.selectBatchIds(ids);
        List<PlatformOrderProductDo> platformOrderProductDos = platformOrderProductDao.selectList(new LambdaQueryWrapper<PlatformOrderProductDo>()
                .in(PlatformOrderProductDo::getOrderId, ids));
        Map<String, List<PlatformOrderProductDo>> itemMap = platformOrderProductDos
                .stream().collect(Collectors.groupingBy(PlatformOrderProductDo::getPlatformOrderNo));
        List<PlatformOrderDto> platformOrders = new ArrayList<>();
        for (PlatformOrderDo platformOrderDo : platformOrderDos) {
            List<PlatformOrderProductDo> itemList = itemMap.get(platformOrderDo.getPlatformOrderNo());
            if (itemList == null) {
                continue;
            }
            PlatformOrderDto platformOrderDto = new PlatformOrderDto();
            BeanUtils.copyProperties(platformOrderDo, platformOrderDto);
            if (platformOrderDto.getPlatformOrderNo().endsWith("-1") || platformOrderDto.getPlatformOrderNo().endsWith("-2") || platformOrderDto.getPlatformOrderNo().endsWith("-3")
                    || platformOrderDto.getPlatformOrderNo().endsWith("-4") || platformOrderDto.getPlatformOrderNo().endsWith("-5") || platformOrderDto.getPlatformOrderNo().endsWith("-6")) {
                platformOrderDto.setPlatformOrderNo(platformOrderDto.getPlatformOrderNo().substring(0, platformOrderDto.getPlatformOrderNo().length() - 2));
            }
            platformOrderDto.setProductDoList(itemList);
            platformOrders.add(platformOrderDto);
        }
        List<MailAccountDo> mailAccountDoList = mailAccountService.getBaseMapper().selectList(new LambdaQueryWrapper<MailAccountDo>()
                .eq(MailAccountDo::getStoreId, storeId).eq(MailAccountDo::getIsAutoSent, 1));
        this.autoSendEmail(mailType, mailAccountDoList, platformOrders);
        return null;
    }
//    final DeliveredStateFuture future = new DeliveredStateFuture();

    public SingleResult autoSendEmail(int mailType, List<MailAccountDo> mailAccountDos, List<PlatformOrderDto> platformOrders) {
        List<OperateRecordDo> operateRecordDos = new ArrayList<>();
        List<MailRecordDo> mailRecordDos=new ArrayList<>();
        Set<Long> templateIds = mailAccountDos.stream().flatMap(ma -> Stream.of(ma.getDefaultSendTemplateId(), ma.getDefaultConfirmTemplateId())).filter(Objects::nonNull).collect(Collectors.toSet());
        Map<Long, FreeMarkerTemplateDo> templateDoMap = new HashMap<>();
        if (!templateIds.isEmpty()) {
            templateDoMap = freeMarkerTemplateDao.selectBatchIds(templateIds).stream().collect(Collectors.toMap(FreeMarkerTemplateDo::getId, i -> i));
        }
        for (MailAccountDo mailAccountDo : mailAccountDos) {

            Session session = null;
            Transport transport = null;

            try {
                session = mailSenderService.initMailSession(mailAccountDo);
                transport = mailSenderService.initMailTransport(mailAccountDo, session);
                Long defaultConfirmTemplateId = mailAccountDo.getDefaultConfirmTemplateId();
                Long defaultSendTemplateId = mailAccountDo.getDefaultSendTemplateId();
                Long storeId = mailAccountDo.getStoreId();
                Long mailAccountId = mailAccountDo.getId();
                Integer emailTitleType = mailAccountDo.getEmailTitleType();
                String context = mailAccountDo.getTitle();
                logger.info("初始化邮箱");
                if (mailType == 1 && defaultConfirmTemplateId == null) {
                    logger.error("默认确认模板ID不能为空: mailAccountDo={}", mailAccountDo);
                    return SingleResult.failure("默认确认模板ID不能为空");
                }
                if (mailType == 2 && defaultSendTemplateId == null) {
                    logger.error("默认发送模板ID不能为空: mailAccountDo={}", mailAccountDo);
                    return SingleResult.failure("默认发送模板ID不能为空");
                }
                String sendMailAddress = mailAccountDo.getMailNo();
                String title = "";
                // String sendMailAddress ="ding@cloudkinto.com";
                for (PlatformOrderDto platformOrder : platformOrders) {
                    MailRecordDo mailRecordDo=new MailRecordDo();
                    logger.info("准备发信");
                    try {
                        // 找到收件人邮箱
                        String receiverEmail = platformOrder.getBuyerEmail();
                     //    String receiverEmail = "llleeedocomo@gmail.com";
                        if (StringUtils.isBlank(receiverEmail)) {
//                            logger.info("收件人邮箱为空: 订单号={}", platformOrder.getPlatformOrderNo());
                            continue;
                        }
                        logger.info("获取发信内容成功");

                        if (mailType == 1) {
                            FreeMarkerTemplateDo confirmFreeMarkerTemplateDo = null;
                            confirmFreeMarkerTemplateDo = templateDoMap.get(defaultConfirmTemplateId);
                            if (confirmFreeMarkerTemplateDo == null) {
                                confirmFreeMarkerTemplateDo = freeMarkerTemplateDao.selectById(defaultConfirmTemplateId);
                            }
                            String mailTitle = confirmFreeMarkerTemplateDo.getMailTitle();
                            //1:前缀 2:后缀
                            if (emailTitleType == 1) {
                                title = context + mailTitle;
                            } else if (emailTitleType == 2) {
                                title = mailTitle + context;
                            } else {
                                title = mailTitle;
                            }
                            //String sendMailTitle = confirmFreeMarkerTemplateDo.getMailTitle();
                            String confirmMessage = sendUserEmail(defaultConfirmTemplateId, platformOrder, sendMailAddress);

                            //拼接头部和尾部
                            confirmMessage = getString(mailAccountId, confirmMessage);
                            confirmMessage = confirmMessage.replaceAll("\\n", "<br>");
                            // 发送确认邮件
                            // mailSenderService.sendEmail(session, transport, title, confirmMessage, receiverEmail);
                            mailSenderService.sendEmail(session, transport, title, confirmMessage, sendMailAddress, receiverEmail);
                            logger.info("确认邮件发送成功: 订单号={}, 收件人={}", platformOrder.getPlatformOrderNo(), receiverEmail);
                            handleMailRecordData(platformOrder, mailRecordDo, defaultConfirmTemplateId, confirmFreeMarkerTemplateDo, storeId, sendMailAddress, receiverEmail);
                            mailRecordDo.setSendStatus(1);
                        } else if (mailType == 2) {
                            FreeMarkerTemplateDo sendFreeMarkerTemplateDo = null;
                            sendFreeMarkerTemplateDo = templateDoMap.get(defaultSendTemplateId);
                            if (sendFreeMarkerTemplateDo == null) {
                                sendFreeMarkerTemplateDo = freeMarkerTemplateDao.selectById(defaultSendTemplateId);
                            }
                            //1 插入模板id
                            mailRecordDo.setTemplateId(defaultSendTemplateId);
                            String sendMailTitle = sendFreeMarkerTemplateDo.getMailTitle();
                            //1:前缀 2:后缀
                            if (emailTitleType == 1) {
                                title = context + sendMailTitle;
                            } else if (emailTitleType == 2) {
                                title = sendMailTitle + context;
                            } else {
                                title = sendMailTitle;
                            }

                            String sendMessage = sendUserEmail(defaultSendTemplateId, platformOrder, sendMailAddress);
                            //拼接头部和尾部
                            sendMessage = getString(mailAccountId, sendMessage);
                            sendMessage = sendMessage.replaceAll("\\n", "<br>");
                            // mailSenderService.sendEmail(session, transport, title, sendMessage, receiverEmail);
                            mailSenderService.sendEmail(session, transport, title, sendMessage, sendMailAddress, receiverEmail);
                            logger.info("发送邮件发送成功: 订单号={}, 收件人={}", platformOrder.getPlatformOrderNo(), receiverEmail);
                            handleMailRecordData(platformOrder, mailRecordDo, defaultSendTemplateId, sendFreeMarkerTemplateDo, storeId, sendMailAddress, receiverEmail);
                            mailRecordDo.setSendStatus(1);

                        }
                        OperateRecordDo operateRecordDo = new OperateRecordDo(platformOrder.getId(), OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_SendMail,
                                null, new Date(), String.format("自动%s配信成功", mailType == 1 ? "确认" : "发货"));
                        operateRecordDos.add(operateRecordDo);
                    } catch (Exception e) {
                        logger.error("{}配信失败: 订单号={}, 收件人={}, 错误信息={}",mailType == 1 ? "确认" : "发货",
                                platformOrder.getPlatformOrderNo(), platformOrder.getReceiver(), e.getMessage(), e);
                        OperateRecordDo operateRecordDo = new OperateRecordDo(platformOrder.getId(), OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_SendMail,
                                null, new Date(), String.format("%s配信失败", mailType == 1 ? "确认" : "发货"));
                        operateRecordDos.add(operateRecordDo);
                        // 邮件记录
                        Long templateId = 0L;
                        if (mailType == 2 && defaultSendTemplateId != null) {
                            templateId = defaultSendTemplateId;
                        } else if (mailType == 1 && defaultConfirmTemplateId != null) {
                            templateId = defaultConfirmTemplateId;
                        }
                        FreeMarkerTemplateDo freeMarkerTemplateDo = null;
                        if (templateId != 0L) {
                            freeMarkerTemplateDo = templateDoMap.get(templateId);
                            if (freeMarkerTemplateDo == null) {
                                freeMarkerTemplateDo = freeMarkerTemplateDao.selectById(templateId);
                            }
                        }
                        String receiverEmail = platformOrder.getBuyerEmail();
                        // 添加空值检查
                        if (freeMarkerTemplateDo != null) {
                            handleMailRecordData(platformOrder, mailRecordDo, templateId, freeMarkerTemplateDo,
                                    storeId, sendMailAddress, receiverEmail);
                        } else {
                            //避免freeMarkerTemplateDo为空
                            handleErrorFreemarker(platformOrder, templateId, mailRecordDo, storeId, sendMailAddress, receiverEmail);
                        }
                        mailRecordDo.setErrorMessage(e.getMessage() != null ? e.getMessage() : e.getClass().getName());
                        mailRecordDo.setSendStatus(0);
                    }finally {
                        if (StaticDict.Store_PlatformCode.Rakuten.getValue().equals(platformOrder.getPlatformCode()) || StaticDict.Store_PlatformCode.Qoo10.getValue().equals(platformOrder.getPlatformCode())) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                Thread.currentThread().interrupt();
                                logger.error("线程被中断: {}", e.getMessage(), e);
                            }
                        }
                        //加入模板记录
                        mailRecordDos.add(mailRecordDo);
                    }

                }
            } catch (Exception e) {
                logger.error("Transport 初始化失败: mailAccountDo={}, 错误信息={}", mailAccountDo, e.getMessage(), e);
            } finally {
                if (transport != null) {
                    try {
                        mailSenderService.transportClose(transport);
                        logger.info("Transport 成功关闭: mailAccountDo={}", mailAccountDo);
                    } catch (Exception e) {
                        logger.error("Transport 关闭失败: mailAccountDo={}, 错误信息={}", mailAccountDo, e.getMessage(), e);
                    }
                }
            }
            //操作记录
            if (!operateRecordDos.isEmpty()) {
                List<List<OperateRecordDo>> partition = ListUtil.partition(operateRecordDos, 3000);
                for (List<OperateRecordDo> partList : partition) {
                    rabbitTemplate.convertAndSend(RabbitQueueConstant.CrossMall_CMOrder_OperateList, JSON.toJSONString(partList));
                }
            }
            if (!mailRecordDos.isEmpty()) {
                // 先过滤掉无效记录
                List<MailRecordDo> validRecords = mailRecordDos.stream()
                        .filter(mailRecordDo -> mailRecordDo.getOrderId() != null)
                        .collect(Collectors.toList());

                if (!validRecords.isEmpty()) {
                    List<List<MailRecordDo>> partition = ListUtil.partition(validRecords, 300);
                    for (List<MailRecordDo> partList : partition) {
                        if (!partList.isEmpty()) {
                            try {
                                mailRecordDao.insertBatch(partList);
                            } catch (Exception e) {
                                logger.error("批量插入邮件记录失败，记录数: {}", partList.size(), e);
                                // 可以考虑逐条插入失败的记录
                            }
                        }
                    }
                }
            }

        }
        return SingleResult.success();
    }

    private void handleErrorFreemarker(PlatformOrderDto platformOrder, Long templateId, MailRecordDo mailRecordDo, Long storeId, String sendMailAddress, String receiverEmail) {
        // 设置基本的邮件记录信息，避免空指针
        TemplatesDo templatesDo = templatesDao.selectById(templateId);
        Long timesStamp = templatesDo.getTimesStamp();
        mailRecordDo.setTemplateName("未知模板");
        mailRecordDo.setStoreId(storeId);
        mailRecordDo.setMailNoSend(sendMailAddress);
        mailRecordDo.setMailNoReceive(receiverEmail);
        mailRecordDo.setTimesStamp(timesStamp);
        mailRecordDo.setTemplateId(templateId);
        mailRecordDo.setPlatformOrderNo(platformOrder.getPlatformOrderNo());
        mailRecordDo.setPlatformCode(platformOrder.getPlatformCode());
        mailRecordDo.setOrderId(platformOrder.getId());
        mailRecordDo.setMailNoReceive(receiverEmail);
        mailRecordDo.setSendMethod(1);
        mailRecordDo.setSendTime(new Date(System.currentTimeMillis()));
    }

    private  void handleMailRecordData(PlatformOrderDto platformOrder, MailRecordDo mailRecordDo, Long templateId, FreeMarkerTemplateDo freeMarkerTemplateDo, Long storeId, String mailAddress, String receiverEmail) {
        //1 插入模板id
        mailRecordDo.setTemplateId(templateId);
        Long timesStamp = templatesDao.selectById(templateId).getTimesStamp();
        mailRecordDo.setTimesStamp(timesStamp);
        //1-2 插入平台单号
        mailRecordDo.setPlatformOrderNo(platformOrder.getPlatformOrderNo());
        mailRecordDo.setPlatformCode(platformOrder.getPlatformCode());
        //1-3 插入模板名称
        mailRecordDo.setTemplateName(freeMarkerTemplateDo.getName());
        //1-4 插入店铺id
        mailRecordDo.setStoreId(storeId);
        //1-5 插入发件人
        mailRecordDo.setMailNoSend(mailAddress);
        //1-6 插入收件人
        mailRecordDo.setRecipient(platformOrder.getReceiver());
        //1-7 插入收件人邮箱
        mailRecordDo.setMailNoReceive(receiverEmail);
        mailRecordDo.setSendMethod(1);
        mailRecordDo.setOrderId(platformOrder.getId());
        mailRecordDo.setSendTime(new Date(System.currentTimeMillis()));
    }


    private String getReceiverEmail(String receiver) {
        String email = platformOrderDao.selectReceiver(receiver);
        return email;

    }

    private String sendUserEmail(Long templateId, PlatformOrderDto platformOrder, String mailNo) {
        try {
            String templateContent = getTemplateContent(templateId);
            templateContent = handleJanpanese(templateContent);
            Configuration cfg = createConfiguration();
            Template template = createTemplate(templateContent, cfg);
            Map<String, Object> dataModel = createDataModel(platformOrder, mailNo);
            return processTemplate(template, dataModel);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            return null; // 或者抛出自定义异常
        }
    }

    private String sendUserEmail2(SendMailReq req, PlatformOrderDto platformOrder) {
        try {
            String templateContent = getTemplateContent2(req);
            templateContent = handleJanpanese(templateContent);
            Configuration cfg = createConfiguration();
            Template template = createTemplate(templateContent, cfg);
            Map<String, Object> dataModel = createDataModel(platformOrder, req.getMailNo());
            return processTemplate(template, dataModel);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            return null; // 或者抛出自定义异常
        }
    }

    private String getTemplateContent2(SendMailReq req) {
        Long templateId = req.getTemplateId();
        Long timesStamp = req.getTimesStamp();

        List<TemplatesContentDo> templatesContentDos = templatesContentDao.selectList(new LambdaQueryWrapper<TemplatesContentDo>().eq(TemplatesContentDo::getTemplateId, templateId)
                .eq(TemplatesContentDo::getTimeStamp, timesStamp));
        if(templatesContentDos.size()==0)
        {
            throw new BizException("模板匹配失败！");
        }
            return templatesContentDos.get(0).getContent();
    }

    //
    // private String sendUserEmail(SendMailReq req) {
    //     try {
    //         String templateContent = getTemplateContent(req.getTemplateId());
    //
    //       templateContent=handleJanpanese(templateContent);
    //
    //
    //         Configuration cfg = createConfiguration();
    //         Template template = createTemplate(templateContent, cfg);
    //         Map<String, Object> dataModel = createDataModel(req);
    //         return processTemplate(template, dataModel);
    //     } catch (IOException | TemplateException e) {
    //         e.printStackTrace();
    //         return null; // 或者抛出自定义异常
    //     }
    // }
    private String handleJanpanese(String templateContent) {
        List<FreeMarkerTemplatePlaceHolderDo> placeHolderList = freeMarkerTemplatePlaceHolderDao.selectList(null);
        // 构建日文占位符到英文占位符的映射，只保留key和value都不为空的占位符
        Map<String, String> placeholderMap = placeHolderList.stream()
                .filter(holder -> StringUtils.isNotBlank(holder.getJapanese()) && StringUtils.isNotBlank(holder.getValue()))
                .collect(Collectors.toMap(
                        FreeMarkerTemplatePlaceHolderDo::getJapanese,
                        FreeMarkerTemplatePlaceHolderDo::getValue,
                        (existing, replacement) -> existing // 处理键冲突的情况
                ));
//        System.out.println("--------------------------------------------");
//        System.out.println(templateContent);
//        System.out.println("---------------------------------------------");
        // 使用StringBuilder来构建新的模板内容
        StringBuilder newTemplateContent = new StringBuilder(templateContent);

        // 遍历占位符映射，替换模板内容
        for (Map.Entry<String, String> entry : placeholderMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            // 使用Pattern.quote来转义特殊字符
            String regex = Pattern.quote(key);
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(newTemplateContent);
            // 使用StringBuffer进行替换
            StringBuffer sb = new StringBuffer();
            while (matcher.find()) {
                matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
            }
            matcher.appendTail(sb);
            newTemplateContent = new StringBuilder(sb.toString());
        }
//        System.out.println("-------------------------------------");
//        System.out.println(newTemplateContent);
//        System.out.println("---------------------------------------");
        return newTemplateContent.toString();
    }


    private String getTemplateContent(Long templateId) {
        FreeMarkerTemplateDo freeMarkerTemplateDo = freeMarkerTemplateDao.selectById(templateId);
        return freeMarkerTemplateDo.getContent();
    }

    private Configuration createConfiguration() {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setDefaultEncoding("UTF-8");
        return cfg;
    }

    private Template createTemplate(String templateContent, Configuration cfg) throws IOException {
        StringReader reader = new StringReader(templateContent);
        return new Template("templateName", reader, cfg);
    }

    private Map<String, Object> createDataModel(PlatformOrderDo platformOrderDo, List<PlatformOrderProductDo> list) {
        Map<String, Object> dataModel = new HashMap<>();
        // 根据平台订单号获取数据模型数据
        handlePlatOrderData(dataModel, platformOrderDo);
        //处理订单下的产品
        //处理订单下的产品,判断其下每一种属性的值是否都有数据没有置为空字符串
        List<PlatformOrderProductDo> resList = new ArrayList<>();
        for (PlatformOrderProductDo platformOrderProductDo : list) {
            PlatformOrderProductDo e = handleProductData(platformOrderProductDo);
            if (e != null)
                resList.add(e);
        }
        // 根据实际情况填充数据模型
        dataModel.put("productList", resList);

        return dataModel;
    }
    /*
     * 对产品列表中的属性做一个预处理对空指针异常问题进行发现
     * */

    private PlatformOrderProductDo handleProductData(PlatformOrderProductDo platformOrderProductDo) {
        if (platformOrderProductDo.getPlatformSku() == null) {
            platformOrderProductDo.setPlatformSku("");
        }
        if (platformOrderProductDo.getSkuType() == 0) {
            return null;
        }
        if (platformOrderProductDo.getPlatformQty() == null) {
            return null;
        }
        if (platformOrderProductDo.getPlatformProductName() == null) {
            platformOrderProductDo.setPlatformProductName("");
        }
        if (platformOrderProductDo.getSku() == null) {
            platformOrderProductDo.setSku("");
        }

        if (platformOrderProductDo.getCurrencyCode() == null) {
            platformOrderProductDo.setCurrencyCode("");
        }
        if (platformOrderProductDo.getItemAmount() == null) {
            return null;
        }

        if (platformOrderProductDo.getItemId() == null) {
            platformOrderProductDo.setItemId("");
        }


        return platformOrderProductDo;
    }

    private Map<String, Object> createDataModel(PlatformOrderDto platInsetItem, String mailNo) {
        Map<String, Object> dataModel = new HashMap<>();
        handleAutoSendPlatOrderData(dataModel, platInsetItem, mailNo);
        return dataModel;
    }

    private void handlePlatOrderData(Map<String, Object> dataModel, PlatformOrderDo platformOrderDo) {
        dataModel.put("receiver", platformOrderDo.getReceiver());
        dataModel.put("telephone", platformOrderDo.getTelephone());
        //将不为空的地址合并
        StringBuilder addressBuilder = new StringBuilder();
        if (platformOrderDo.getAddressOne() != null) {
            addressBuilder.append(platformOrderDo.getAddressOne());
        }
        if (platformOrderDo.getAddressTwo() != null) {
            addressBuilder.append(platformOrderDo.getAddressTwo());
        }
        if (platformOrderDo.getAddressTri() != null) {
            addressBuilder.append(platformOrderDo.getAddressTri());
        }
        dataModel.put("address", addressBuilder.toString());
        dataModel.put("countryRegionCode", platformOrderDo.getCountryRegionCode());
        dataModel.put("cityCode", platformOrderDo.getCityCode());
        dataModel.put("district", platformOrderDo.getDistrict());
        dataModel.put("postcode", platformOrderDo.getPostcode());
        dataModel.put("storeId", platformOrderDo.getStoreId());
        //根据店铺id找到店铺名称
        PlatformStoreDo platformStoreDo = platformStoreDao.selectById(platformOrderDo.getStoreId());
        dataModel.put("storeName", platformStoreDo.getStoreName());
        dataModel.put("buyerEmail", platformOrderDo.getBuyerEmail());
        dataModel.put("orderNo", platformOrderDo.getOrderNo());
        //platformOrderDo.getOrderTime()时间格式为2025-04-01 00:11:38
        // 格式化 orderTime
        Date orderTime = platformOrderDo.getOrderTime();
        if (orderTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedOrderTime = dateFormat.format(orderTime);
            dataModel.put("orderTime", formattedOrderTime);
        }

        Date shipTime = platformOrderDo.getShipTime();
        if (shipTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedShipTime = dateFormat.format(shipTime);
            dataModel.put("shipTime", formattedShipTime);
        }
        dataModel.put("reqPrice", platformOrderDo.getReqPrice());
        Date payTime = platformOrderDo.getPayTime();
        if (payTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedPayTime = dateFormat.format(payTime);
            dataModel.put("payTime", formattedPayTime);
        }
        Date createTime = platformOrderDo.getCreateTime();
        if (createTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedCreateTime = dateFormat.format(createTime);
            dataModel.put("createTime", formattedCreateTime);
        }
        dataModel.put("platformOrderNo", platformOrderDo.getPlatformOrderNo());
        dataModel.put("currencyCode", platformOrderDo.getCurrencyCode());
        dataModel.put("platformSku", platformOrderDo.getPlatformSku());
        dataModel.put("platformCode", platformOrderDo.getPlatformCode());
        dataModel.put("totalAmount", platformOrderDo.getTotalAmount());
        //todo 转变日期格式
        String deliveryDateString = platformOrderDo.getDeliveryDate();
        if (StringUtils.isNotBlank(deliveryDateString)) {
            try {
                // 假设原始字符串是类似 "Sat Nov 08 00:00:00 CST 2025" 的格式
                SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
                Date date = inputFormat.parse(deliveryDateString);

                // 格式化为目标格式
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = outputFormat.format(date);

                dataModel.put("deliveryDate", formattedDate);
            } catch (ParseException e) {
                logger.warn("无法解析 deliveryDate: {}", deliveryDateString, e);
                dataModel.put("deliveryDate", deliveryDateString); // 保留原始值
            }
        } else {
            dataModel.put("deliveryDate", "");
        }
     //   dataModel.put("deliveryDate", platformOrderDo.getDeliveryDate());

        //店铺联系人邮箱
        Long storeId = platformOrderDo.getStoreId();
        ShopDo shopDo = shopDao.selectById(storeId);
        String shopContactEmail = shopDo.getShopContactEmail();
        dataModel.put("shopContactEmail", shopContactEmail);

        if (platformOrderDo.getCoupon() != null && platformOrderDo.getCoupon().compareTo(BigDecimal.ZERO) > 0) {
            dataModel.put("coupon", platformOrderDo.getCoupon().negate());
        } else {
            dataModel.put("coupon", platformOrderDo.getCoupon());
        }
        //如果point大于0,就把它变为负数
        if (platformOrderDo.getPoint() != null && platformOrderDo.getPoint().compareTo(BigDecimal.ZERO) > 0) {
            dataModel.put("point", platformOrderDo.getPoint().negate());
        } else {
            dataModel.put("point", platformOrderDo.getPoint());
        }
        if (platformOrderDo.getPoint() == null || platformOrderDo.getPoint() == BigDecimal.ZERO) {
            dataModel.put("isPoint", "なし");
        } else {
            dataModel.put("isPoint", "あり");
        }

        // 计算订单金额小计
        BigDecimal totalAmount = platformOrderDo.getTotalAmount() != null ? platformOrderDo.getTotalAmount() : BigDecimal.ZERO;
        BigDecimal postagePrice = platformOrderDo.getPostagePrice() != null ? platformOrderDo.getPostagePrice() : BigDecimal.ZERO;
        BigDecimal subtotalBillAmount = totalAmount.add(postagePrice);
        dataModel.put("subtotalBillAmount", subtotalBillAmount);

        dataModel.put("postagePrice", platformOrderDo.getPostagePrice());
        dataModel.put("settlementModel", platformOrderDo.getSettlementModel());
        dataModel.put("reqPriceTax", platformOrderDo.getReqPriceTax());
        dataModel.put("trackNo", platformOrderDo.getTrackNo());
        dataModel.put("remark", platformOrderDo.getRemark());
        Date reserveBeginTime = platformOrderDo.getReserveBeginTime();
        if (reserveBeginTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedReserveBeginTime = dateFormat.format(reserveBeginTime);
            dataModel.put("reserveBeginTime", formattedReserveBeginTime);
        }

        Date reserveEndTime = platformOrderDo.getReserveEndTime();
        if (reserveEndTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedReserveEndTime = dateFormat.format(reserveEndTime);
            dataModel.put("reserveEndTime", formattedReserveEndTime);
        }
        dataModel.put("defaultDeliveryCompanyCode", platformOrderDo.getDefaultDeliveryCompanyCode());
        dataModel.put("shipBy", platformOrderDo.getShipBy());
        dataModel.put("logisticsCarrier", platformOrderDo.getLogisticsCarrier());
        //合计计算
        BigDecimal totalAmountEnd = platformOrderDo.getReqPriceTax()
                .add(platformOrderDo.getPostagePrice())
                .add(platformOrderDo.getCoupon())
                .add(platformOrderDo.getPoint())
                .add((platformOrderDo.getTotalAmount()));
        dataModel.put("totalAmountEnd", totalAmountEnd);
        Long channelId = platformOrderDo.getChannelId();
        if (channelId != null) {
            LogisticsChannelDo logisticsChannelDo = logisticsChannelDao.selectById(channelId);

            String channelName = logisticsChannelDo.getChannelName();
            dataModel.put("channelChineseName", channelName);
//            if(channelName.equals("黑猫投涵"))
//            {
//                dataModel.put("channelName", "黒猫のメッセージ");
//            }else if(channelName.equals("投涵多件")){
//                dataModel.put("channelName", "複数を収容する");
//            }else if(channelName.equals("黑猫宅急便")){
//                dataModel.put("channelName", "黒猫の宅急便");
//            }else if(channelName.equals("邮局")){
//                dataModel.put("channelName", "郵便局");
//            }else if(channelName.equals("佐川宅急便")){
//                dataModel.put("channelName", "佐川急便");
//            }else{
//                dataModel.put("channelName", logisticsChannelDo.getChannelName());
//            }
            dataModel.put("channelName", logisticsChannelDo.getChannelName());

        }
    }

    private void handleAutoSendPlatOrderData(Map<String, Object> dataModel, PlatformOrderDto platformOrderDo, String mailNo) {
        dataModel.put("receiver", platformOrderDo.getReceiver());
        dataModel.put("telephone", platformOrderDo.getTelephone());
        //将不为空的地址合并
        StringBuilder addressBuilder = new StringBuilder();
        if(platformOrderDo.getDistrict() !=null)
        {
            addressBuilder.append(platformOrderDo.getDistrict());
        }
        if(platformOrderDo.getCityCode()!=null)
        {
            addressBuilder.append(platformOrderDo.getCityCode());
        }
        if (platformOrderDo.getAddressOne() != null) {
            addressBuilder.append(platformOrderDo.getAddressOne());
        }
        if (platformOrderDo.getAddressTwo() != null) {
            addressBuilder.append(platformOrderDo.getAddressTwo());
        }
        if (platformOrderDo.getAddressTri() != null) {
            addressBuilder.append(platformOrderDo.getAddressTri());
        }
        dataModel.put("address", addressBuilder.toString());
        dataModel.put("countryRegionCode", platformOrderDo.getCountryRegionCode());
        dataModel.put("cityCode", platformOrderDo.getCityCode());
        dataModel.put("district", platformOrderDo.getDistrict());
        dataModel.put("postcode", platformOrderDo.getPostcode());
        dataModel.put("storeId", platformOrderDo.getStoreId());
        //根据店铺id找到店铺名称
        PlatformStoreDo platformStoreDo = platformStoreDao.selectById(platformOrderDo.getStoreId());
        dataModel.put("storeName", platformStoreDo.getStoreName());
        dataModel.put("buyerEmail", platformOrderDo.getBuyerEmail());
        dataModel.put("orderNo", platformOrderDo.getOrderNo());
        dataModel.put("shipBy", platformOrderDo.getShipBy());
        //platformOrderDo.getOrderTime()时间格式为2025-04-01 00:11:38
        // 格式化 orderTime
        Date orderTime = platformOrderDo.getOrderTime();
        if (orderTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedOrderTime = dateFormat.format(orderTime);
            dataModel.put("orderTime", formattedOrderTime);
        }

        Date shipTime = platformOrderDo.getShipTime();
        if (shipTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedShipTime = dateFormat.format(shipTime);
            dataModel.put("shipTime", formattedShipTime);
        }
        dataModel.put("reqPrice", platformOrderDo.getReqPrice());
        Date payTime = platformOrderDo.getPayTime();
        if (payTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedPayTime = dateFormat.format(payTime);
            dataModel.put("payTime", formattedPayTime);
        }
        Date createTime = platformOrderDo.getCreateTime();
        if (createTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedCreateTime = dateFormat.format(createTime);
            dataModel.put("createTime", formattedCreateTime);
        }
        dataModel.put("platformOrderNo", platformOrderDo.getPlatformOrderNo());
        dataModel.put("currencyCode", platformOrderDo.getCurrencyCode());
        dataModel.put("platformSku", platformOrderDo.getPlatformSku());
        dataModel.put("platformCode", platformOrderDo.getPlatformCode());
        dataModel.put("totalAmount", platformOrderDo.getTotalAmount());
        //todo deleveryDate(varchar)改变日期格式Sat Nov 08 00:00:00 CST 2025变为2025-11-07 07:18:59
      //  dataModel.put("deliveryDate", platformOrderDo.getDeliveryDate());
        String deliveryDateString = platformOrderDo.getDeliveryDate();

        if (StringUtils.isNotBlank(deliveryDateString)) {
            try {
                // 假设原始字符串是类似 "Sat Nov 08 00:00:00 CST 2025" 的格式
                SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
                Date date = inputFormat.parse(deliveryDateString);

                // 格式化为目标格式
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = outputFormat.format(date);

                dataModel.put("deliveryDate", formattedDate);
            } catch (ParseException e) {
                logger.warn("无法解析 deliveryDate: {}", deliveryDateString, e);
                dataModel.put("deliveryDate", deliveryDateString); // 保留原始值
            }
        } else {
            dataModel.put("deliveryDate", "");
        }


        Date reserveBeginTime = platformOrderDo.getReserveBeginTime();
        if (reserveBeginTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedReserveBeginTime = dateFormat.format(reserveBeginTime);
            dataModel.put("reserveBeginTime", formattedReserveBeginTime);
        }

        Date reserveEndTime = platformOrderDo.getReserveEndTime();
        if (reserveEndTime != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedReserveEndTime = dateFormat.format(reserveEndTime);
            dataModel.put("reserveEndTime", formattedReserveEndTime);
        }
        dataModel.put("defaultDeliveryCompanyCode", platformOrderDo.getDefaultDeliveryCompanyCode());
        dataModel.put("logisticsCarrier", platformOrderDo.getLogisticsCarrier());
        // 计算订单金额小计
        BigDecimal totalAmount = platformOrderDo.getTotalAmount() != null ? platformOrderDo.getTotalAmount() : BigDecimal.ZERO;
        BigDecimal postagePrice = platformOrderDo.getPostagePrice() != null ? platformOrderDo.getPostagePrice() : BigDecimal.ZERO;
        BigDecimal subtotalBillAmount = totalAmount.add(postagePrice);

       //合计计算

        BigDecimal totalAmountEnd = platformOrderDo.getReqPrice();
                /*.add(platformOrderDo.getPostagePrice())
                .add(platformOrderDo.getCoupon())
                .add(platformOrderDo.getPoint())
                .add((platformOrderDo.getTotalAmount()));*/
        //todo 待解决 totalAmount totalAmountEnd 模板小计和合计是反的
        //如果是乐天 合计=totalAmountEnd-积分 否则不减
        if (platformOrderDo.getPlatformCode().equals("rakuten")) {
        if(platformOrderDo.getPoint() != null) {
            totalAmountEnd = totalAmountEnd.subtract(platformOrderDo.getPoint());
        }}
        dataModel.put("reqPrice", totalAmountEnd);

        dataModel.put("totalAmount", totalAmount);

        if (platformOrderDo.getCoupon() != null && platformOrderDo.getCoupon().compareTo(BigDecimal.ZERO) > 0) {
            dataModel.put("coupon", platformOrderDo.getCoupon().negate());
        } else {
            dataModel.put("coupon", platformOrderDo.getCoupon());
        }
        //如果point大于0,就把它变为负数
        if (platformOrderDo.getPoint() != null && platformOrderDo.getPoint().compareTo(BigDecimal.ZERO) > 0) {
            dataModel.put("point", platformOrderDo.getPoint().negate());
        } else {
            dataModel.put("point", platformOrderDo.getPoint());
        }
        if (platformOrderDo.getPoint() == null || platformOrderDo.getPoint().compareTo(BigDecimal.ZERO) == 0) {
            dataModel.put("isPoint", "なし");
        } else {
            dataModel.put("isPoint", "あり");
        }

        dataModel.put("postagePrice", platformOrderDo.getPostagePrice());
        dataModel.put("settlementModel", platformOrderDo.getSettlementModel());
        dataModel.put("reqPriceTax", platformOrderDo.getReqPriceTax());
        dataModel.put("trackNo", platformOrderDo.getTrackNo());
        dataModel.put("remark", platformOrderDo.getRemark());

        Long channelId = platformOrderDo.getChannelId();
        if (channelId != null) {
            LogisticsChannelDo logisticsChannelDo = logisticsChannelDao.selectById(channelId);
           //特殊处理 如果channelcode是yamoto_one 和 yamoto_two 渠道名称为 ネコポス
            String channelCode = logisticsChannelDo.getChannelCode();
            String channelName = logisticsChannelDo.getChannelName();
            if(channelCode.equals("yamato_one") || channelCode.equals("yamato_more"))
            {
                channelName="ネコポス";
            }
            dataModel.put("channelChineseName", channelName);
//            if(channelName.equals("黑猫投涵"))
//            {
//                dataModel.put("channelName", "黒猫のメッセージ");
//            }else if(channelName.equals("投涵多件")){
//                dataModel.put("channelName", "複数を収容する");
//            }else if(channelName.equals("黑猫宅急便")){
//                dataModel.put("channelName", "黒猫の宅急便");
//            }else if(channelName.equals("邮局")){
//                dataModel.put("channelName", "郵便局");
//            }else if(channelName.equals("佐川宅急便")){
//                dataModel.put("channelName", "佐川急便");
//            }else{
//                dataModel.put("channelName", logisticsChannelDo.getChannelName());
//            }
//            dataModel.put("channelName", logisticsChannelDo.getChannelName());
            dataModel.put("channelName", channelName);

        }

        dataModel.put("buyerName",platformOrderDo.getBuyerName());
        dataModel.put("buyerEmail",platformOrderDo.getBuyerEmail());
        dataModel.put("buyerTelephone",platformOrderDo.getBuyerTelephone());
        dataModel.put("buyerAddress",platformOrderDo.getBuyerAddress());
        dataModel.put("buyerPostcode",platformOrderDo.getBuyerPostcode());
        //店铺联系人邮箱

        dataModel.put("sendEmail", mailNo);
        List<PlatformOrderProductDo> resList = new ArrayList<>();

        if(platformOrderDo.getProductDoList() != null)
        {
            for (PlatformOrderProductDo platformOrderProductDo : platformOrderDo.getProductDoList()) {
                PlatformOrderProductDo e = handleProductData(platformOrderProductDo);
                if (e != null)
                    resList.add(e);
            }
        }
        dataModel.put("productList", resList);
    }

    private String processTemplate(Template template, Map<String, Object> dataModel) throws IOException, TemplateException {
        // 获取模板内容
        String templateString = template.toString();

        // 使用正则表达式查找所有占位符及其周围的 <p> 标签
        // Pattern pattern = Pattern.compile("\\{\\s*(\\w+)\\s*\\}");
        Pattern pattern = Pattern.compile("\\$\\{\\s*(\\w+)\\s*\\}");
        Matcher matcher = pattern.matcher(templateString);

        // 创建一个新的模板字符串，移除不存在或为空的占位符及其周围的标签
        StringBuffer newTemplateString = new StringBuffer();
        //todo:产品列表为空的字段没有排除
        while (matcher.find()) {
            String placeholder = matcher.group(1).trim();
            Object value = dataModel.get(placeholder);
            if (value == null || (value instanceof String && StringUtils.isBlank((String) value))) {
                // 如果占位符对应的值为空，则移除该占位符及其周围的 <p> 标签
                matcher.appendReplacement(newTemplateString, "");
            } else {
                // matcher.appendReplacement(newTemplateString, matcher.group(0));
                //appendReplacement方法使用不能包含$需要将其转译
                matcher.appendReplacement(newTemplateString, Matcher.quoteReplacement(matcher.group(0)));

            }
        }
        matcher.appendTail(newTemplateString);
        // 创建新的模板对象
        StringReader reader = new StringReader(newTemplateString.toString());
        Template newTemplate = new Template("templateName", reader, template.getConfiguration());

        // 处理模板
        StringWriter out = new StringWriter();
        newTemplate.process(dataModel, out);
        //将out.getBuffer().toString()中所有$字符替换为""

        return out.getBuffer().toString();
        //return out.getBuffer().toString().replace("$","");
    }


}



